package com.liliudong.keelflower.upms.biz.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.keelflower.common.core.utils.CacheUtils;
import com.liliudong.keelflower.upms.biz.dao.sys.SysMenuDao;
import com.liliudong.keelflower.upms.biz.entity.sys.SysMenu;
import com.liliudong.keelflower.upms.biz.service.sys.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统菜单 服务实现类
 * </p>
 *
 * @author liudong.li
 * @since 2021-06-07
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenu> implements SysMenuService {

    private final RedisTemplate<String, SysMenu> sysMenuRestTemplate;

    @Override
    public Set<String> getUserPermissionsByUserId(Long userId, boolean isSuperAdmin) {
        return this.getUserMenusByUserId(userId, isSuperAdmin).stream()
                .map(SysMenu::getMenuAuthority)
                .collect(Collectors.toSet());
    }

    @Override
    public List<SysMenu> getUserMenusByUserId(Long userId, boolean isSuperAdmin) {
        HashOperations<String, String, List<SysMenu>> hashOperations = sysMenuRestTemplate.opsForHash();
        String cacheKey = CacheUtils.SysUser.user(userId);
        List<SysMenu> sysMenus = hashOperations.get(cacheKey, CacheUtils.SysUser.MENUS);
        if (CollectionUtil.isEmpty(sysMenus)) {
            if (isSuperAdmin) {
                sysMenus = baseMapper.selectList(null);
            } else {
                sysMenus = baseMapper.selectListByUserId(userId);
            }
            if (CollectionUtil.isNotEmpty(sysMenus)) {
                hashOperations.put(cacheKey, CacheUtils.SysUser.MENUS, sysMenus);
            }
        }
        return sysMenus;
    }
}
